package cn.jieruoda.eb.system.service;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.jieruoda.eb.system.domain.entity.SystemAdmin;
import cn.jieruoda.eb.system.domain.repository.SystemAdminRepository;
import cn.jieruoda.eb.system.domain.repository.SystemRoleMenuRepository;
import cn.jieruoda.eb.system.domain.repository.SystemRoleRepository;
import cn.jieruoda.eb.system.dto.LoginRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class AdminLoginService implements InitializingBean {
    final SystemRoleRepository systemRoleRepository;
    final SystemAdminRepository systemAdminRepository;
    final SystemRoleMenuRepository systemRoleMenuRepository;

    /**
     * 登录
     *
     * @param request
     * @return
     */
    public SaResult doLogin(LoginRequest request) {
        SystemAdmin systemAdmin = systemAdminRepository.findByUsernameAndStatus(request.getUsername(), 1);
        if (systemAdmin == null) {
            return SaResult.error("登录失败");
        }
        String securePwd = SaSecureUtil.sha256(SaSecureUtil.md5(request.getPassword()));
        if (!systemAdmin.getPassword().equals(securePwd)) {
            return SaResult.error("登录失败");
        }
        StpUtil.login(systemAdmin.getId());

        // 构建前端所需的登录响应数据
        Map<String, Object> loginData = new HashMap<>();
        loginData.put("token", StpUtil.getTokenInfo().getTokenValue());

        // 用户信息
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", systemAdmin.getId());
        userInfo.put("username", systemAdmin.getUsername());
        userInfo.put("realName", systemAdmin.getRealName());
        userInfo.put("phone", systemAdmin.getPhone());
        userInfo.put("level", systemAdmin.getLevel());
        loginData.put("userInfo", userInfo);

        // 权限列表 - 这里可以根据实际需求从角色中解析权限
        if ("admin".equals(systemAdmin.getUsername())) {
            List<String> permissions = Arrays.asList("*", "sys:admin:create");
            loginData.put("permissions", permissions);
        } else {
            loginData.put("permissions", Arrays.asList("test"));
        }

        // 角色列表
        List<String> roles = Arrays.asList(systemAdmin.getRoles().split(","));
        loginData.put("roles", roles);

        return SaResult.data(loginData);
    }

    @Override
    public void afterPropertiesSet() {
        Page<SystemAdmin> anyOne = systemAdminRepository.findAll(PageRequest.of(0, 1));
        if (anyOne.isEmpty()) {
            SystemAdmin admin = new SystemAdmin();
            admin.setId(0);
            admin.setUsername("admin");
            admin.setPassword(SaSecureUtil.sha256(SaSecureUtil.md5("123456")));
            admin.setRealName("admin");
            admin.setRoles("admin");
            admin.setLastIp("");
            admin.setLastTime(new Date());
            admin.setCreateTime(new Date());
            admin.setLevel(999);
            admin.setStatus(1);
            admin.setPhone("");
            admin.setEnableSms(true);
            systemAdminRepository.save(admin);
            log.info("init superAdmin success");
        }
    }
}
